#ifndef UARTCORE_H
#define UARTCORE_H
#include <QObject>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QMessageBox>
#include <QDebug>
#include <QQueue>
#include <QFile>
#include <QTextStream>
#include <QDateTime>
#include <QMutex>

#include <iostream>
#include <string>
#include <sstream>

#include "uart_read_work.h"
#include "uart_ring_buffer.h"

using UartNamespace::CharRingBuffer;

#define UART_RING_BUFFER_SIZE (2048)

namespace patch
{
  template < typename T > std::string to_string( const T& n )
  {
    std::ostringstream stm ;
    stm << n ;
    return stm.str() ;
  }
}
namespace UartNamespace {
#define QUEUE_EMPTY (-1)
#define QUEUE_SUCCESS (0)

class Uartcore:public QObject
{
  Q_OBJECT
  QThread workerThread;
public:
  Uartcore(QObject *parent= nullptr);
  ~Uartcore();
  QStringList UartPortScan();
  bool open(QString serial_name, int baud_rate, int data_bit, int parity_bit, int stop_bit, int flow_control);
  void close();
  void write(QByteArray &data);
  QByteArray UartBufferRead();
  void UartReadBufferClean();
  QByteArray HexStringToByteArray(QString HexString);
  void UnInit();
  void UartBufferWrite(QByteArray data);
  void UartBufferReady();

public:
  QString serial_name_;
  int baud_rate_      = 115200;
  int data_bits_      = 8;
  int parity_bits_    = 0;
  int stop_bits_      = 1;
  int flow_control_   = 0;

signals:
  void UartDataReadReadySignal();
  void operate(const int);

public slots:
  void ReadUpperCpuUartData();

  //处理线程执行的结果
  void handleResults(const int rslt) {
      qDebug()<<"receive the resultReady signal---------------------------------";
      qDebug()<<"     current thread ID:"<<QThread::currentThreadId()<<'\n';
      qDebug()<<"     the last result is:"<<rslt;
  }
private:
  void SaveFileInit(QString serial_name, QString &folder_path);
  void SaveUartReadDataToFile(const QByteArray data, size_t data_length);
private:
  QSerialPort *serial_port_ = nullptr;
  QFile save_file_;
  CharRingBuffer ring_buffer_;

};
}
#endif // UARTCORE_H

